﻿# ------------------------------ #
# IP Routing Table Configuration #
# ------------------------------ #
param([string]$virtualMachineService, [string]$virtualMachineName)

Write-Information "Virtual machine '$virtualMachineName' executing IP routing table '$($script.type)' configuration ... " -NoNewLine $true
$session = Get-VirtualMachineInstancePowerShellSession -Subscription $subscription -VirtualMachineName $virtualMachineName
switch ($script.type)
{
	"Add"
	{
        # Add IP routing table entry
		Invoke-Command -Session $session -ScriptBlock {
		    param([string]$destination, [string]$netmask, [string]$gateway, [string]$metric, [string]$interface, [string]$clear, [string]$persist)
            $routes = ROUTE PRINT $destination | Out-String
            if ($routes.IndexOf($destination) -eq -1)
            {
                $verb = "ADD"
            }
            else
            {
                $verb = "CHANGE"
            }
            $flags = ""
            if ($clear -eq $true)
            {
                $flags += "-f "
            }
            if ($persist -eq $true)
            {
                $flags += "-p "
            }
            $command = "ROUTE $flags$verb $destination MASK $netmask $gateway"
            if (![String]::IsNullOrEmpty($metric))
            {
                $command += " METRIC $metric"
            }
            if (![String]::IsNullOrEmpty($interface))
            {
                $command += " IF $interface"
            }
            Invoke-Expression -Command $command | Out-Null
		} -ArgumentList $script.destination, $script.netmask, $script.gateway, $script.metric, $script.interface, $script.clear, $script.persist
	}
	"Remove"
	{
        # Remove IP routing table entry
		Invoke-Command -Session $session -ScriptBlock {
		    param([string]$destination, [string]$clear)
            $routes = ROUTE PRINT $destination | Out-String
            if ($routes.IndexOf($destination) -ne -1)
            {
                $flags = ""
                if ($clear -eq $true)
                {
                    $flags += "-f "
                }
                $command = "ROUTE $($flags)DELETE $destination"
                Invoke-Expression -Command $command | Out-Null
            }
		} -ArgumentList $script.destination, $script.clear
	}
	default
	{
		throw "IP routing table type '$($script.type)' is not supported."
	}
}
Remove-PSSession $session
Write-Text "done."